package com.gjy.controller;

import com.gjy.poi.entity.HW;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2022-11-17 16:15:28
 */
@RestController
@RequestMapping("/excel")
public class ExcelController {

    private static final Integer SUM = 10000;

    @GetMapping("/sxssf2")
    public void sxssf2(HttpServletRequest request,
                       HttpServletResponse response) throws IllegalAccessException, IOException {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("sheet1");
        for (int i = 0; i < SUM; i++) {
            XSSFRow row = sheet.createRow(i);
            otr(list.get(i), row);
        }

        ServletOutputStream os = response.getOutputStream();
        response.setHeader("Content-Type", "application/x-download");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode("登记信息导出表", "utf8") + ".xlsx");
        workbook.write(os);
        os.close();
    }

    @GetMapping("/sxssf")
    public void sxssf(HttpServletRequest request,
                      HttpServletResponse response) throws IllegalAccessException, IOException {
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        SXSSFSheet sheet = workbook.createSheet("sheet1");
        for (int i = 0; i < SUM; i++) {
            SXSSFRow row = sheet.createRow(i);
            otr(list.get(i), row);
        }

        String realPath = request.getSession().getServletContext().getRealPath("/") + "cache" + File.separator;
        String realName = realPath + "登记信息导出表.xlsx";
        System.out.println("realPath = " + realPath);
        Path p1 = Paths.get(realPath);
        if (!Files.exists(p1)) {
            Files.createDirectories(p1);
        }
        try (FileOutputStream fos = new FileOutputStream(realName)) {
            workbook.write(fos);
        } catch (Exception e) {
            Files.delete(p1);
            throw new RuntimeException(e);
        }

        if (Files.deleteIfExists(Paths.get(realName))) {
            System.out.println("删除缓存文件: " + realName);
            if (Files.deleteIfExists(p1)) {
                System.out.println("删除缓存路径: " + realPath);
            }
        }


        response.setHeader("content-Type", "application/x-download");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode("登记信息导出表", StandardCharsets.UTF_8.name()) + ".xlsx");

        ServletOutputStream outputStream = response.getOutputStream();
        try (FileInputStream fis = new FileInputStream(realName)) {
            int len;
            byte[] buffer = new byte[1024];
            while ((len = fis.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        outputStream.flush();
    }

    private static final List<HW> list = new ArrayList<>(SUM);

    static {
        HW hw = new HW();
        hw.setId(100000);
        hw.setName("HW");
        hw.setK5("k5");
        hw.setN3(LocalDateTime.now());
        hw.setB3(BigDecimal.valueOf(1000));
        for (int i = 0; i < SUM; i++) {
            list.add(hw);
        }
    }

    private void otr(HW hw, Row row) throws IllegalAccessException {
        Field[] fields = hw.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            fields[i].setAccessible(true);
            Cell cell = row.createCell(i);
            Object o = fields[i].get(hw);
            if (o instanceof String) {
                cell.setCellValue(((String) o));
            } else if (o instanceof LocalDateTime) {
                cell.setCellValue(((LocalDateTime) o));
            } else if (o instanceof BigDecimal) {
                cell.setCellValue(((BigDecimal) o).doubleValue());
            } else if (o instanceof Boolean) {
                cell.setCellValue(((Boolean) o));
            } else if (o instanceof Integer) {
                cell.setCellValue(((Integer) o));
            }
        }
    }
}
